package com.cloud.nio;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

public class FileChannel {

    public static void main(String[] args) {
        String str = "hello world！";
        // 创建一个输出流->channel
        try {
            FileOutputStream fileOutputStream = new FileOutputStream("d:\\file01.txt");

            // 通过 fileOutputStream 获取对应的 FileChannel
            // 这个 filechannel 真实类型是 FileChannelImpl
            java.nio.channels.FileChannel fileChannel = fileOutputStream.getChannel();

            //创建一个缓冲区
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            // 将 str 写入到 ByteBuffer
            byteBuffer.put(str.getBytes());

            // 对byteBuffer进行flip
            byteBuffer.flip();

            // 将byteBuffer，数据写入到 fileChannel
            fileChannel.write(byteBuffer);

            // 关闭流
            fileOutputStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
